package com.yuzhi.master.drainRRmst.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuzhi.common.contant.Constants;
import com.yuzhi.common.core.page.PageDataInfo;
import com.yuzhi.common.util.StringUtils;
import com.yuzhi.master.drainCorrelation.domain.vo.DrainCorrelationVo;
import com.yuzhi.master.drainCorrelation.service.IDrainCorrelationService;
import com.yuzhi.master.drainRRmst.domain.DrainRRmst;
import com.yuzhi.master.drainRRmst.domain.bo.DrainRRmstBo;
import com.yuzhi.master.drainRRmst.domain.request.DrainRRmstReq;
import com.yuzhi.master.drainRRmst.domain.vo.DrainRRmstVo;
import com.yuzhi.master.drainRRmst.domain.vo.FacilitylogDto;
import com.yuzhi.master.drainRRmst.mapper.IDraRRmstMapper;
import com.yuzhi.master.drainRRmst.service.IDrainRRmstService;
import com.yuzhi.master.sewage.wmst.domain.DrainStatistics;
import com.yuzhi.master.sewage.wmst.service.DrainWmstService;
import com.yuzhi.master.trunkMain.domain.vo.TrunkMainVo;
import com.yuzhi.master.trunkMain.service.ITrunkMainService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class DrainRRmstServiceImpl implements IDrainRRmstService {

    @Autowired
    private IDraRRmstMapper baseMapper;

    @Autowired
    private ITrunkMainService iTrunkMainService;

    @Autowired
    private IDrainCorrelationService iDrainCorrelationService;

    private final DrainWmstService drainWmstService;

    @Override
    public DrainRRmstVo queryById(String id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public PageDataInfo<DrainRRmstVo> queryPageList(DrainRRmstReq request) {
        LambdaQueryWrapper<DrainRRmst> lqw = buildQueryWrapper(request);
        Page<DrainRRmstVo> result = baseMapper.selectVoPage(request.getPageQuery().build(), lqw);
        return PageDataInfo.build(result);
    }

    @Override
    public List<DrainRRmstVo> queryList(DrainRRmstReq request) {
        LambdaQueryWrapper<DrainRRmst> lqw = buildQueryWrapper(request);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DrainRRmst> buildQueryWrapper(DrainRRmstReq request) {
        LambdaQueryWrapper<DrainRRmst> lqw = Wrappers.lambdaQuery();
        // 添加条件查询
        lqw.eq(DrainRRmst::getDeleted, Constants.UNDELETED);
        // 排水设施类型
        lqw.eq(StringUtils.isNotBlank(request.getDrainageLb()), DrainRRmst::getDrainageLb, request.getDrainageLb());
        // 排水设施名称
        lqw.eq(StringUtils.isNotBlank(request.getDrainageId()), DrainRRmst::getDrainageId, request.getDrainageId());

        return lqw;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(DrainRRmstBo bo) {
        if (ObjectUtils.isEmpty(bo)) {
            throw new RuntimeException("参数不能为空");
        }
        DrainRRmst add = BeanUtil.toBean(bo, DrainRRmst.class);
        validEntityBeforeSave(add);
        return baseMapper.insert(add) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(DrainRRmstBo bo) {
        if (ObjectUtils.isEmpty(bo)) {
            throw new RuntimeException("参数不能为空");
        }
        DrainRRmst update = BeanUtil.toBean(bo, DrainRRmst.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    private void validEntityBeforeSave(DrainRRmst entity) {
        // 数据校验逻辑
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            // 业务校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public DrainStatistics getSttpCount() {

        Long paikou = baseMapper.wmstCount();
        Map<String, Long> sttpCount = baseMapper.getSttpCount();
        DrainStatistics drainStatistics = new DrainStatistics();

        drainStatistics.setShuizhi(sttpCount.get("shuizhi"));
        drainStatistics.setLiuliang(sttpCount.get("liuliang"));
        drainStatistics.setYuliang(sttpCount.get("yuliang"));
        drainStatistics.setPaikou(paikou);
        return drainStatistics;
    }

    @Override
    public boolean insertFacilitylog(String deviceId, String msg) {
        FacilitylogDto dto = new FacilitylogDto();
        // 1. 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        // 2. 定义格式（例如：yyyy-MM-dd HH:mm:ss）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 3. 转换为字符串
        String formattedDateTime = now.format(formatter);
        dto.setId(UUID.randomUUID().toString());
        dto.setDeviceId(deviceId);
        dto.setMag(msg);
        dto.setInsertionTime(formattedDateTime);
        return baseMapper.insertFacilitylog(dto);
    }

    @Override
    public Boolean deleteById(String id, Boolean isValid) {
        if (isValid) {
            // 业务校验
        }
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    public DrainRRmstVo selectDrainRRmstByStcd(String stcd) {
        LambdaQueryWrapper<DrainRRmst> lqw = Wrappers.lambdaQuery();
        lqw.eq(DrainRRmst::getStcd, stcd);
        lqw.eq(DrainRRmst::getDeleted, 0);
        DrainRRmst drainRRmst = baseMapper.selectOne(lqw);
        return BeanUtil.toBean(drainRRmst, DrainRRmstVo.class);
    }

    @Override
    public DrainRRmstVo findNearestRainfallStation(BigDecimal longitude, BigDecimal latitude) {
        DrainRRmst nearestStation = baseMapper.findNearestRainfallStation(longitude, latitude);
        return BeanUtil.toBean(nearestStation, DrainRRmstVo.class);
    }

    @Override
    public List<Map<String, Object>> trunkMainStationNames() {
        List<TrunkMainVo> trunkMains = iTrunkMainService.queryBachList();
        List<Map<String, Object>> result = new ArrayList<>();

        if (CollUtil.isEmpty(trunkMains)) {
            return result;
        }

        for (TrunkMainVo trunkMainVo : trunkMains) {
            String trunkmainId = trunkMainVo.getTrunkmainId();
            if (StrUtil.isBlank(trunkmainId)) {
                continue;
            }

            List<DrainCorrelationVo> correlations = iDrainCorrelationService.queryByTrunkmainId(trunkmainId);
            if (CollUtil.isEmpty(correlations)) {
                Map<String, Object> item = new HashMap<>();
                item.put("trunkmainId", trunkmainId);
                item.put("trunkmainName", trunkMainVo.getTrunkmainName());
                item.put("stcd", null);
                item.put("stnm", null);
                result.add(item);
                continue;
            }

            for (DrainCorrelationVo correlation : correlations) {
                String stcd = correlation.getStcd();
                String stnm = null;
                if (StrUtil.isNotBlank(stcd)) {
                    DrainRRmstReq rmstReq = new DrainRRmstReq();
                    rmstReq.setStcd(stcd);
                    List<DrainRRmstVo> stations = this.queryList(rmstReq);
                    if (CollUtil.isNotEmpty(stations)) {
                        stnm = stations.get(0).getStnm();
                    }
                }

                Map<String, Object> item = new HashMap<>();
                item.put("trunkmainId", trunkmainId);
                item.put("trunkmainName", trunkMainVo.getTrunkmainName());
                item.put("stcd", stcd);
                item.put("stnm", stnm);
                result.add(item);
            }
        }

        return result;
    }

    private int getFKeyTypeBySttp(String sttp) {
        if ("1".equals(sttp)) return 3; // 水质
        if ("2".equals(sttp)) return 6; // 流量
        if ("3".equals(sttp)) return 4; // 液位
        if ("4".equals(sttp)) return 7; // 雨量
        return -1;
    }

}
